﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using CarlosAg.ExcelXmlWriter;
using App.Core.DB;

/// <summary>
/// Summary description for ExcelExporter
/// </summary>
public static class DataExporter
{
    /// <summary>
    /// Exports a DataTable to a Excel Spread Sheet
    /// </summary>
    /// <param name="dt"></param>
    /// <returns>Returns the Newly Created File Name with the Exported Data</returns>
    public static String ToExcel(System.Data.DataTable dt, IList<int?> ignoredFieldIndexes, bool addColumnHeader)
    {
        Workbook book = new Workbook();
        Worksheet sheet = book.Worksheets.Add("Sheet1");
        if (dt != null && dt.Rows.Count > 0)
        {
            if (addColumnHeader)
            {
                WorksheetRow headerRow = sheet.Table.Rows.Add();
                addHeaderRow(headerRow, dt, ignoredFieldIndexes);
            }

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                WorksheetRow row = sheet.Table.Rows.Add();
                System.Data.DataRow dtRow = dt.Rows[i];
                addDataRow(row, dtRow, ignoredFieldIndexes);
            }
        }                

        //row.Cells.Add("Hello World");        

        String fileName = String.Format("{0}.xls", System.Guid.NewGuid().ToString());
        String filePath = HttpContext.Current.Server.MapPath(AppConstants.TEMP_DIRECTORY);
        if (!System.IO.Directory.Exists(filePath))
            System.IO.Directory.CreateDirectory(filePath);

        filePath = System.IO.Path.Combine(filePath, fileName);

        book.Save(filePath);

        return filePath;
    }
    public static String ToExcel(DataRow[] rows, IList<int?> ignoredFieldIndexes, bool addColumnHeader)
    {
        Workbook book = new Workbook();
        Worksheet sheet = book.Worksheets.Add("Sheet1");        
        if (rows != null && rows.Length > 0)
        {
            DataTable dt = rows[0].Table;
            if (addColumnHeader)
            {
                WorksheetRow headerRow = sheet.Table.Rows.Add();
                addHeaderRow(headerRow, dt, ignoredFieldIndexes);
            }

            for (int i = 0; i < rows.Length; i++)
            {
                WorksheetRow row = sheet.Table.Rows.Add();
                System.Data.DataRow dtRow = rows[i];
                addDataRow(row, dtRow, ignoredFieldIndexes);
            }
            //row.Cells.Add("Hello World");
            String fileName = String.Format("{0}.xls", System.Guid.NewGuid().ToString());
            String filePath = HttpContext.Current.Server.MapPath(AppConstants.TEMP_DIRECTORY);
            if (!System.IO.Directory.Exists(filePath))
                System.IO.Directory.CreateDirectory(filePath);

            filePath = System.IO.Path.Combine(filePath, fileName);
            book.Save(filePath);
            return filePath;
        }        
        return String.Empty;
    }
    private static void addHeaderRow(WorksheetRow row, System.Data.DataTable dt, IList<int?> ignoredFieldIndexes)
    {
        //foreach (System.Data.DataColumn column in dt.Columns)
        for(int i=0; i< dt.Columns.Count; i++)
        {
            if (ignoredFieldIndexes == null || ignoredFieldIndexes.Count == 0 || ignoredFieldIndexes.SingleOrDefault(P => P == i) == null)
                row.Cells.Add(dt.Columns[i].ColumnName);
        }
    }
    private static void addDataRow(WorksheetRow row, System.Data.DataRow dtRow, IList<int?> ignoredFieldIndexes)
    {
        for (int i = 0; i < dtRow.ItemArray.Length; i++)// object data in dtRow.ItemArray)
        {
            if (ignoredFieldIndexes == null || ignoredFieldIndexes.Count == 0 || ignoredFieldIndexes.SingleOrDefault(P => P == i) == null)            
                row.Cells.Add(ConvertToString(dtRow[i]));
            //else if()
            //    row.Cells.Add(ConvertToString(dtRow[i]));
        }
    }
    private static String ConvertToString(object data)
    {
        if (data.GetType() == typeof(String))
            return WebUtil.FormatText(NullHandler.GetString(data));
        else if (data.GetType() == typeof(DateTime))
            return NullHandler.GetDateTime(data).ToString(AppConstants.ValueOf.DATE_FROMAT_DISPLAY);
        else if (data.GetType() == typeof(decimal))
            return String.Format(AppConstants.ValueOf.DECIMAL_FORMAT, NullHandler.GetDecimal(data));
        else
            return NullHandler.GetString(data);
    }
    /// <summary>
    /// Exports a DataTable to a CSV file
    /// </summary>
    /// <param name="dt"></param>
    /// <returns>Returns the Newly Created File Name with the Exported Data</returns>
    public static String ToCSV(System.Data.DataTable dt)
    {
        String fileName = String.Format("{0}.csv", System.Guid.NewGuid().ToString());
        ///TODO: Add the Implementation Codes
        return fileName;
    }
}
